package com.ktwlrj.core.feign.headerimpl;

import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import com.ktwlrj.core.feign.strategy.header.ISetHeaderStrategy;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员中心请求头设置token实现
 *
 * @author TY
 */
@Component("mcSetToken")
@Slf4j
public class McSetTokenImpl implements ISetHeaderStrategy {
    /**
     * token KEY
     **/
    private static final String TOKEN_KEY = "Authorization";
    /**
     * feign传递设置dataKey
     */
    private static final String DATA_KEY_FEIGN = "terminal_data_key";

    @Override
    public void setHeader(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        if (request == null) {
            return;
        }
        String token = getToken(request);
        log.debug("--------------McSetTokenImpl-------------token:{}", token);
        if (StringUtils.isNotBlank(token)) {
            template.header(TOKEN_KEY, token);
        }
        String dataKey = request.getParameter(DATA_KEY_FEIGN);
        if (StringUtils.isBlank(dataKey)) {
            dataKey = (String) request.getAttribute(DATA_KEY_FEIGN);
        }
        if (StringUtils.isNotBlank(dataKey)) {
            template.header(DATA_KEY_FEIGN, dataKey);
        }
    }


    /**
     * 获取token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = null;
        token = request.getHeader(TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(TOKEN_KEY);
        }
        if (StringUtils.isBlank(token)) {
            throw new ActionException(ResultCode.AUTH_SESSION_TIMEOUT);
        }
        return token;
    }
}
